package com.ds.lens.data.configuration;

import com.ds.lens.data.filter.CrossDomainFilter;
import com.ds.lens.data.filter.ValidateFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

/**
 * @author Gerald Kou
 * @date 2019-05-09
 */
@Slf4j
@Configuration
@SuppressWarnings("unchecked")
public class FilterConfiguration {

    @Bean
    public Filter AuthFilter() {
        return new ValidateFilter();    //权限验证过滤器
    }

    @Bean
    @Order(HIGHEST_PRECEDENCE)   //必须先处理跨域请求！
    public FilterRegistrationBean crossDomainFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        CrossDomainFilter httpBasicFilter = new CrossDomainFilter();
        registrationBean.setFilter(httpBasicFilter);
        List<String> urlPatterns = new ArrayList<>();
        urlPatterns.add("/*");
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }

    @Bean
    @Order  //默认最后执行
//    public FilterRegistrationBean validateFilterRegistrationBean(ValidateFilter validateFilter) {
    public FilterRegistrationBean validateFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(AuthFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }

}
